package com.gitee.easyopen.util;

import java.util.Arrays;
import java.util.List;

import com.gitee.easyopen.bean.Pagable;

public class ListUtil {


    /**
     * 分页
     * 
     * @param list
     *            待分页list
     * @param pageIndex
     * @param pageSize 如果为0，返回原list
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T extends Pagable> List<T> page(List<T> list, int pageIndex, int pageSize) {
        if (pageSize == 0) {
            return list;
        } else {
            int start = (int) ((pageIndex - 1) * pageSize); // 起始位置
            int total = list.size(); // 总记录数
            int leftLimit = total - start; // 剩余长度
            int limit = pageSize > leftLimit ? leftLimit : pageSize; // 偏移量

            Pagable[] arr = list.toArray(new Pagable[total]);
            Pagable[] newArr = new Pagable[limit];

            System.arraycopy(arr, start, newArr, 0, limit);

            return (List<T>) Arrays.asList(newArr);
        }
    }
}
